package com.wl.controller;

import com.wl.pojo.User;
import com.wl.service.LoginService;
import com.wl.utils.JwtUtils;
import com.wl.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 后台账号密码登陆接口
     * @param user 实体类
     * @return 返回用户id和jwt令牌
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User isUser = loginService.getUserInfo(user);

        if(isUser != null) {
            if(isUser.getStatus() == 0) {
                return Result.error("您的账号已被封禁，请联系管理员");
            }
            // 返回数据
            return Result.success(builderReturnData(isUser));
        } else {
            return Result.error("账号或密码错误");
        }
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/login/get/user")
    public Result getUserInfo(Integer userId) {
        return Result.success(loginService.getUserInfoById(userId));
    }

    /**
     * 注册接口
     */
    @PostMapping("/register")
    public Result Register(@RequestBody User user) {
        User isUser = loginService.addUserInfo(user);
        return Result.success(builderReturnData(isUser));
    }


    private Map<String, Object> builderReturnData(User user) {
        Map<String, Object> claims = new HashMap<>();
        // 自定义JWT信息
        claims.put("userId", user.getUserId());
        claims.put("username", user.getUsername());
        // 使用JWT工具类，生成身份令牌
        String token = JwtUtils.generateJwt(claims);
        // 准备返回的数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("userId", user.getUserId());
        responseData.put("token", token);
        return responseData;
    }
}
